package com.demon.encrypt.lock;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author Rao
 * @Date 2020/6/16
 * 简单实现自旋锁
 **/
public class SpinLock {

    private final AtomicReference<Thread> owner = new AtomicReference<>();
    private int count = 0;

    /**
     * 加锁
     */
    public void lock(){
        Thread current = Thread.currentThread();

        if(current == owner.get()){
            count++;
            return;
        }

        while (! owner.compareAndSet(null,current)){

        }
    }

    /**
     * 解锁
     */
    public void unlock(){
        Thread current = Thread.currentThread();

        if (current == owner.get()){
            count--;
            if(count == 0) {
                owner.compareAndSet(current, null);
            }
        }

    }
}
